<template>
	<view class="publishDemand">
		<uni-forms ref="valiForm" :modelValue="valiFormData">
			<!-- 展示接收的手机号（脱敏处理） -->
			<view class="title">
				当前手机号
				<text class="subtitle">{{ maskedPhone }}</text>
			</view>
			<view class="publishDemand-content">
				<view class="formLabel no-border uni-flex border-bottom">
					<text>新手机号</text>
					<uni-forms-item name="tel">
						<uni-easyinput class="my-input" v-model="valiFormData.tel" placeholder="请输入新手机号"
							@input="checkPhoneInput" />
					</uni-forms-item>
				</view>
				<view class="formLabel no-border uni-flex bankCode border-bottom">
					<text>验证码</text>
					<uni-forms-item name="code">
						<uni-easyinput class="my-input" v-model="valiFormData.code" placeholder="请输入验证码" />
					</uni-forms-item>
					<view class="help-text" @click="getCode" :style="{ 
							background: (valiFormData.tel && countDown === 0) ? '#2F80ED' : '#B3D3FF',
							opacity: (valiFormData.tel && countDown === 0) ? 1 : 0.7
						}" :class="{
							'disabled': !(valiFormData.tel && countDown === 0)
						}">
						{{ countDown > 0 ? `${countDown}s后重新获取` : '获取验证码' }}
					</view>
				</view>
			</view>
		</uni-forms>

		<view class="publishDemand-button" @click="submit('valiForm')">确定</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		editPhone,
		sendSmsCode
	} from "@/api/ModifyPhone.js";


	// 表单数据
	const valiFormData = reactive({
		tel: '',
		code: '',
	})

	// 存储原始手机号和脱敏后手机号
	const originalPhone = ref('');
	const maskedPhone = ref(''); // 脱敏后展示用
	const countDown = ref(0); // 倒计时计时器
	let timer = null; // 定时器实例
	// 组件挂载后从本地存储读取手机号（核心修改）
	onMounted(() => {
		// 从本地存储获取 user_info
		const userInfoStr = uni.getStorageSync('user_info');
		if (userInfoStr) {
			try {
				const userInfo = JSON.parse(userInfoStr);
				originalPhone.value = userInfo.phone || '';
				// 脱敏处理
				if (originalPhone.value) {
					maskedPhone.value = originalPhone.value.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3');
				} else {
					maskedPhone.value = '未绑定手机号';
				}
			} catch (e) {
				// 处理 JSON 解析失败的异常
				console.error('解析 user_info 失败:', e);
				maskedPhone.value = '用户信息格式错误';
			}
		} else {
			maskedPhone.value = '未获取到用户信息';
		}
	});

	// 手机号验证正则
	const isPhoneValid = (phone) => {
		return /^1[3-9]\d{9}$/.test(phone);
	};

	// 检查手机号输入状态
	const checkPhoneInput = () => {
		// 可以在这里添加输入验证逻辑
	};

	// 获取验证码方法
	const getCode = () => {
		// 验证新手机号是否填写正确
		if (!valiFormData.tel) {
			uni.showToast({
				icon: 'none',
				title: '请输入新手机号'
			});
			return;
		}

		// 验证手机号格式
		if (!isPhoneValid(valiFormData.tel)) {
			uni.showToast({
				icon: 'none',
				title: '请输入正确的手机号'
			});
			return;
		}

		// 调用发送验证码接口（query参数方式）
		sendSmsCode(valiFormData.tel)
			.then(res => {
				if (res.code === 200) {
					uni.showToast({
						icon: 'none',
						title: res.msg || '验证码已发送！'
					});
					// 开始倒计时
					startCountDown();
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg || '验证码发送失败'
					});
				}
			})
			.catch(err => {
				console.error('发送验证码失败:', err);
				uni.showToast({
					icon: 'none',
					title: res.msg || '网络异常，请稍后重试'
				});
			});
	};

	// 倒计时功能
	const startCountDown = () => {
		countDown.value = 60; // 60秒倒计时
		// 清除之前的定时器
		if (timer) clearInterval(timer);

		timer = setInterval(() => {
			countDown.value--;
			if (countDown.value <= 0) {
				clearInterval(timer);
				timer = null;
			}
		}, 1000);
	};

	// 提交表单
	const submit = () => {
		if (valiFormData.tel === "") {
			uni.showToast({
				icon: "none",
				title: "请输入手机号"
			});
		} else if (valiFormData.code === "") {
			uni.showToast({
				icon: "none",
				title: "请输入验证码"
			});
		} else if (!isPhoneValid(valiFormData.tel)) {
			uni.showToast({
				icon: "none",
				title: "请输入正确的手机号"
			});
		} else {
			// 调用修改手机号接口
			editPhone({
				mobile: valiFormData.tel,
				// newMobile: valiFormData.tel, // 新增：传递新手机号
				code: valiFormData.code
			}).then((res) => {
				if (res.code === 200) {
					uni.showToast({
						icon: "none",
						title: res.msg || '手机号修改成功！'
					});
					// 更新本地存储的用户信息
					const userInfo = JSON.parse(uni.getStorageSync('user_info') || '{}');
					userInfo.phone = valiFormData.tel;
					uni.setStorageSync('user_info', JSON.stringify(userInfo));
					uni.navigateBack();
				} else {
					uni.showToast({
						icon: "none",
						title: res.msg || "修改失败"
					});
				}
			}).catch(err => {
				console.error('修改手机号失败:', err);
				uni.showToast({
					icon: "none",
					title: res.msg || "网络异常，请稍后重试"
				});
			});
		}
	};

	// 页面卸载时清除定时器
	onUnmounted(() => {
		if (timer) {
			clearInterval(timer);
		}
	});
</script>

<style lang="scss">
	.formLabel {
		.uni-forms-item {
			flex: 1;
			margin-bottom: 30rpx;
		}
	}

	.bankCode {
		padding-bottom: 20rpx;

		.uni-forms-item {
			flex: 1;
			margin-bottom: 0rpx;
		}
	}

	.no-border {
		.uni-forms-item__content .is-input-border {
			border: none !important;
			font-size: 28rpx;
			margin-top: 6rpx;
		}
	}
</style>

<style scoped lang="scss">
	.publishDemand {
		padding: 26rpx 24rpx 81rpx;
		background: #ffffff;
		min-height: calc(100vh - 26rpx);

		.title {
			font-weight: 500;
			font-size: 30rpx;
			color: #303133;
			margin: 47rpx 0 67rpx;

			.subtitle {
				font-weight: 400;
				font-size: 26rpx;
				color: #999999;
				margin-left: 14rpx;
			}
		}

		.publishDemand-content {
			background: #FFFFFF;
			border-radius: 20rpx;
			margin-bottom: 24rpx;

			.no-border {
				margin-bottom: 29rpx;
			}

			.border-bottom {
				border-bottom: 1px solid #E2E2E2;
			}

			.formLabel {
				.slectBank {
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;
				}

				.help-text {
					border-radius: 34rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #fff;
					width: 200rpx;
					height: 67rpx;
					text-align: center;
					line-height: 67rpx;
					margin-left: 44rpx;

					/* 禁用状态样式 */
					&.disabled {
						opacity: 0.7;
						cursor: not-allowed;
					}
				}

				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #303133;
					line-height: 80rpx;
					min-width: 120rpx;
				}
			}

		}

		.publishDemand-button {
			width: 100%;
			height: 88rpx;
			background: #2F80ED;
			border-radius: 44rpx;
			text-align: center;
			font-weight: 600;
			font-size: 30rpx;
			color: #FFFFFF;
			line-height: 88rpx;
			margin: 0 auto;
			margin-top: 192rpx;
		}
	}
</style>